/**
 * @FileName: BrandValidator.java
 * @Author
 * @Description:
 * @Date 2016年5月3日 下午2:27:53
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.validator.admin;

import java.util.Date;

import com.jfinal.core.Controller;
import com.jfinal.validate.Validator;

import cn.hpclub.server.model.Brand;

public class BrandValidator extends Validator{
    @Override
    protected void validate(Controller c){
        validateName(c);
        validateCreateTime(c);
    }

    /**
     * @Title: validateCreateTime
     * @Description:校验创建时间
     */

    private void validateCreateTime(Controller c){
        validateRequired("brand.create_time", "brandCreateTimeMessages", "创建时间不能为空");
        Date createTime = c.getParaToDate("brand.create_time");
        if(new Date().before(createTime)){// 创建时间还比现在晚
            addError("brandCreateTimeMessages", "创建时间不可能晚于现在，请重新选择");
        }
    }

    /**
     * @Title: validateName
     * @Description:校验名称
     */

    private void validateName(Controller c){
        validateRequired("brand.name", "brandNameMessages", "名称不能为空");
        validateRegex("brand.name", "^[\u4e00-\u9fa5_a-zA-Z0-9_]{1,32}$", "brandNameMessages",
                      "品牌的名称为1-32个字母、汉字、数字、下划线的组合");
        String name = c.getPara("brand.name");
        String id = c.getPara("brand.id");
        Brand brand = null;
        if(c.getParaToBoolean("isAdd")){
            brand = Brand.dao.findFirst("select id from brand b where b.name=?", name);
        } else{
            brand = Brand.dao.findFirst("select id from brand b where b.name=? and b.id <>?", name, id);
        }
        if(brand != null){// 说明已经存在这个名字
            addError("brandNameMessages", "名称不能重复，已存在" + name);
        }
    }

    @Override
    protected void handleError(Controller c){
        if(!c.getParaToBoolean("isAdd")){
            c.keepModel(Brand.class);
        }
        c.render("/admin/brand_input.tpl");
    }

}
